<template>
  <div id="app" class="chat-container">
    <!-- 左侧侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <span>对话列表</span>
      </div>
      <div class="sidebar-content">
        <!-- 显示对话列表 -->
        <div v-for="(conversation, index) in conversations" :key="index" @click="selectConversation(index)" class="conversation-item">
          {{ conversation[0].content.substring(0, 10) }}... <!-- 显示部分对话内容 -->
        </div>
      </div>
    </div>

    <!-- 右侧内容区域 -->
    <div class="main-content">
      <h1>智能助手对话页面</h1>
      <div class="border-container">
        <!-- 对话消息展示区域 -->
        <div v-for="(message, index) in currentConversation" :key="index" class="message-container">
          <div v-if="message.role === 'USER'" >
            <span>您：</span>
            <p class="user-message">{{ message.content }}</p>
          </div>
          <div v-else-if="message.role === 'ASSISTANT'">
            <span>智能助手：</span>
            <p  class="assistant-message">{{ message.content }}</p>
          </div>
        </div>
      </div>

      <!-- 输入框和发送按钮 -->
      <div class="input-container">
        <input type="text" v-model="userInput" @keyup.enter="sendMessage" class="input-field">
        <button @click="sendMessage" class="send-button">发送</button>
      </div>

      <!-- 加载遮罩层 -->
      <div v-if="showOverlay" class="overlay">
        <div class="loader"></div> <!-- 加载图标 -->
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  name: 'ChatPage',
  data() {
    return {
      messages: [], // 存储所有对话消息
      userInput: '', // 用户输入的消息
      rep: null, // 请求返回的响应数据
      showOverlay: false, // 控制加载遮罩层的显示
      currentConversationIndex: null // 当前选中的对话索引
    };
  },
  computed: {
    conversations() {
      let conversationList = [];
      let currentConversation = [];
      let lastMessageTime = null;
      // 遍历所有消息，根据时间将其分组为对话列表
      for (const message of this.messages) {
        if (!lastMessageTime || (message.timestamp - lastMessageTime) < 60000) {
          currentConversation.push(message);
        } else {
          conversationList.push(currentConversation);
          currentConversation = [message];
        }
        lastMessageTime = message.timestamp;
      }
      if (currentConversation.length > 0) {
        conversationList.push(currentConversation);
      }
      return conversationList;
    },
    currentConversation() {
      // 根据当前选中的对话索引获取当前对话的内容
      return this.currentConversationIndex !== null ? this.conversations[this.currentConversationIndex] : [];
    }
  },
  mounted() {
    // 页面加载时从本地存储中获取对话记录
    const savedMessages = localStorage.getItem('chatMessages');
    if (savedMessages) {
      this.messages = JSON.parse(savedMessages);
    }
  },
  methods: {
    async sendMessage() {
      if (this.userInput.trim() === '') return;
      const userMessage = { role: 'USER', content: this.userInput, timestamp: Date.now() };
      this.messages.push(userMessage);
      try {
        this.showOverlay = true;
        this.rep = await request({
          url: '/professor/chat',
          method: 'post',
          data: this.userInput,
          timeout: 60000
        });
        const assistantMessage = { role: 'ASSISTANT', content: this.rep.output.choices[0].message.content, timestamp: Date.now() };
        this.messages.push(assistantMessage);
        // 将对话记录存储到本地存储中
        localStorage.setItem('chatMessages', JSON.stringify(this.messages));
        this.currentConversationIndex = this.conversations.length - 1;
      } catch (error) {
        console.error('Error:', error);
        this.$message.error('An error occurred. Please try again.');
      } finally {
        this.showOverlay = false;
      }
      this.userInput = '';
    },
    selectConversation(index) {
      // 点击对话列表中的项目时，设置当前选中的对话索引
      this.currentConversationIndex = index;
    }
  }
};
</script>


<style scoped>
/* 整体布局 */
.chat-container {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: flex-start;
}

/* 左侧侧边栏样式 */
.sidebar {
  width: 15%;
  height: 661px;
  background: linear-gradient(to bottom right,#dbe6fb, #f3f4f8);
  border-right: 1px solid #ccc;
  transition: width 0.3s ease; /* 添加过渡效果 */
}
.sidebar-header {
  text-align: center;
  color: #000000;
  padding: 10px;
}
.sidebar-content {
  padding: 10px;
  overflow-y: auto;
  max-height: calc(100vh - 100px); /* 根据实际高度调整 */
}
.conversation-item {
  padding: 10px 10px;
  margin-top: 10px;
  cursor: pointer;
  background-color: rgba(111, 84, 84, 0);
  color: #000000;
  transition: background-color 0.3s ease;
}
.conversation-item:hover {
  background-color: #ddd;
}

/* 右侧内容区域样式 */
.main-content {
  width: 100%;
  height: 660px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
  background: linear-gradient(to bottom right,#dbe6fb, #f3f4f8);
}
.border-container {
  width: 100%;
  margin-left: 20px;
  overflow: auto;
  height: calc(100vh - 200px); /* 根据实际高度调整 */
}

/* 输入框和发送按钮样式 */
.input-container {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-top: 10px;
}
.input-field {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
.send-button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #007bff;
  color: #fff;
  cursor: pointer;
  margin-left: 10px;
}

/* 加载遮罩层样式 */
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.5); /* 半透明白色 */
  z-index: 999; /* 确保遮罩层在最顶层 */
  display: flex;
  justify-content: center;
  align-items: center;
}
.loader {
  border: 8px solid #f3f3f3; /* Light grey */
  border-top: 8px solid #3498db; /* Blue */
  border-radius: 50%;
  width: 50px;
  height: 50px;
  animation: spin 2s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 对话消息样式 */
.message-container {
  margin-bottom: 10px;
}
.user-message {
  background-color: RGB(93,92,222);
  color: #fff;
  padding: 10px;
  border-radius: 5px;
  max-width: 90%;
  margin-left: 0;
  margin-right: auto;
}
.assistant-message {
  background-color: #F0F0F0;
  color: #333;
  padding: 10px;
  border-radius: 5px;
  max-width: 90%;
  margin-left: 0;
  margin-right: auto;
}
</style>
